package cn.itcast.web.timingmail;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.system.User;
import cn.itcast.web.controller.BaseController;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/email")
public class TimingMail extends BaseController {
    //注入购销合同
    @Autowired
    private ContractDao contractDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private UserDao userDao;

    @RequestMapping("/deliveryPeriod")
    public String execute() {


        //1.得到当前时间,去数据库匹配
        Date d = new Date();
        //三天后
        long time = d.getTime() + 1000 * 60 * 60 * 24 * 3;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(time);
        System.out.println(date);

        //2.手动注入
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext-dao.xml");
        //注入contractDao
        contractDao = (ContractDao) context.getBean("contractDao");
        //输入userDao,查询email
        userDao = (UserDao) context.getBean("userDao");


        //3.查询数据库
        List<Contract> contracts = this.contractDao.findByDeliveryPeriod(date);
        //判断
        if (contracts != null && contracts.size() > 0) {
            //4.遍历
            for (Contract contract : contracts) {
                //4.1
                //得到合同号
                String contractNo = contract.getContractNo();
                //得到创建的id
                String id = contract.getCreateBy();
                //查询一个用户
                User user = userDao.findById(id);

                //4.2创建一个集合,封装数据
                Map<String, String> map = new HashMap<>();
                map.put("title", "SAAS-平台管理小助手提醒您!");
                map.put("content", "温馨提醒您,您有一份购销合同到" + date + "即将到期,合同号是" + contractNo + "请您提前准备好!SAAS-管理平台提醒您");
                map.put("email", user.getEmail());

                //4.3发送邮件
                rabbitTemplate.convertAndSend("msg.email", map);

            }

        }
        return "redirect:/cargo/contract/list";
    }

}
